package com.hancher.gamelife2.weather;

import android.content.res.AssetManager;

import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.base.BaseApplication;
import com.hancher.common.javautil.EmptyUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

/**
 * 作者：Hancher
 * 时间：2020/9/27 0027 下午 1:47
 * 邮箱：ytu_shaoweijie@163.com
 * <p>
 * 说明：用于获取assets中的天气图片
 */
public class WeatherIconHelper {

    //asset中使用
    static String WEATHER_ICON_CSV_ASSET_PATH = "weather/weather_icon2.csv";
    static String prefix = "weather/weathericon/%s";

    /**
     * 1.通过天气字符串，是否是夜间，获取图片路径
     * @param weatherStr 晴
     * @param isNight 是否是夜间
     * @return file:///android_asset/weather/weathericon/150-fill.svg-fill.svg
     * @throws IOException 文件异常
     */
    public static String getAssetPathByWeatherStr(String weatherStr, boolean isNight) throws IOException {
        AssetManager assetManager = BaseApplication.getInstance().getAssets();
        InputStream in = assetManager.open(WEATHER_ICON_CSV_ASSET_PATH);
        return getAssetPicPathByWeatherStrCsv(in, weatherStr, isNight);
    }


    /**
     * 读取并写入csv
     * @throws IOException
     */
    public static String getAssetPicPathByWeatherStrCsv(InputStream in, String weatherStr, boolean isNight) throws IOException {
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        long lineNum = 0;
        String[] head = null;
        String[] line = null;
        String picPath = String.format(prefix, "999.png");
        while (true) {
            String strLine = br.readLine();
            if (EmptyUtil.isEmpty(strLine))
                break;
            if (lineNum == 0) {
                head = strLine.split(",");
            } else if (lineNum > 0) {
                line = strLine.split(",");
                HashMap<String, String> map = new HashMap<>();
                for (int i = 0; i < head.length; i++) {
                    map.put(head[i], line[i]);
                }
                try {
                    if (weatherStr.equals(map.get("天气"))) {
                        if (Integer.parseInt((isNight ? map.get("夜晚") : map.get("白天"))) > 0) {
                            picPath = String.format(prefix, map.get("图标代码"));
                        }
                    }
                } catch (Exception e) {
                    LogUtil.e("err:", e);
                }
            }
            lineNum++;
        }
        return picPath;
    }
}
